# coding=utf-8
import platform
import sys
import threading
from datetime import datetime

import tornado.escape
import tornado.web
from tornado import ioloop
from tornado.httpserver import HTTPServer

from framework.utilities import get_cmd_params, to_int
from services.cat_service.question_bank import QuestionBank
from setting import is_debug
from urls import GLOBAL_URLS

if platform.system().upper() == 'WINDOWS' and int(platform.python_version_tuple()[0] + platform.python_version_tuple()[1]) >= 38:
    from asyncio import set_event_loop_policy, WindowsSelectorEventLoopPolicy

    set_event_loop_policy(WindowsSelectorEventLoopPolicy())


def main(urls, port):
    app = tornado.web.Application(urls,
                                  cookie_secret="UKJ%^&*^#*768712aui1ll12____@#!#",
                                  xsrf_cookie=True,
                                  debug=is_debug,
                                  gzip=True
                                  )

    # 启动服务器
    server = HTTPServer(app)  # 100Mb
    server.listen(port)

    print('启动计划...')
    threading.Thread(target=QuestionBank.update_memory_banks_periodic).start()

    print('运行在端口 : ' + str(port))
    ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    try:
        params = get_cmd_params(sys.argv)
        port = to_int(params.get('-port')) if not is_debug else 9000

        print(datetime.now())
        if not port:
            print('[失败]请指定端口')
        else:
            main(GLOBAL_URLS, port)
    except Exception as e:
        print('启动服务', e)
